'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async followadd() {
    const { ctx } = this;
    const { uid, followerid } = ctx.request.body;
    if (!(uid && followerid)) {
      return ctx.body = { success: false, msg: '信息不完整' };
    }
    try {
      await ctx.model.Follow.create({
        uid,
        followerid,
      });
      ctx.body = { success: true, msg: '关注成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '关注失败' };
    }
  }

  async followfind() {
    const { ctx } = this;
    const { uid, followerid } = ctx.request.body;
    const where = {};
    if (uid) {
      where.uid = uid;
    }
    if (followerid) {
      where.followerid = followerid;
    }
    try {
      await ctx.model.Follow.belongsTo(ctx.model.User, {
        foreignKey: 'uid',
        targetKey: 'uid',
      });
      const res = await ctx.model.Follow.findAll({
        where,
        include: [{
          model: ctx.model.User,
          attributes: {
            exclude: [ 'pas' ],
          },
        }],
      });
      for (const item of res) {
        const follow = await ctx.model.User.findOne({
          where: {
            uid: item.followerid,
          },
          attributes: {
            exclude: [ 'pas' ],
          },
        });
        item.setDataValue('follower', follow);
      }
      ctx.body = { success: true, data: res };
    } catch (e) {
      ctx.body = { success: false, data: '查询失败' };
    }
  }

  async unfollow() {
    const { ctx } = this;
    const { followid, uid, followerid } = ctx.request.body;
    if (!(followid || (uid && followerid))) {
      ctx.body = { success: false, msg: '请传入必要参数' };
    }
    const where = {};
    if (followid) {
      where.followid = followid;
    }
    if (uid) {
      where.uid = uid;
    }
    if (followerid) {
      where.followerid = followerid;
    }
    try {
      await ctx.model.Follow.destroy({
        where,
      });
      ctx.body = { success: true, msg: '取关成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '取关失败' };
    }
  }

}

module.exports = HomeController;
